package net.dntuan.training.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * This class replaces web.xml file in Servlet 3.0
 * 
 * @author tuan.dang
 * 
 */
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { MultiHttpSecurityConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { WebAppConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    /**
     * This class replaces dispatcher-servlet.xml file
     * 
     */
    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = { "net.dntuan.training.spring.mvc" })
    public static class WebAppConfig extends WebMvcConfigurerAdapter {

        /**
         * Configure an internalResouceViewResolver. This resolver is required to use Spring MVC with jsp view
         * 
         * @return InternalResourceViewResolver
         */
        @Bean
        public InternalResourceViewResolver configureInternalResourceViewResolver() {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/jsp/");
            resolver.setSuffix(".jsp");
            return resolver;
        }

        @Override
        public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }
    }
}
